输出管理
首先梳理下项目的目录结构。
根目录包括2个文件package.json和webpack.config.js,包含3个文件夹:src(资源文件,index.js为入口文件)、dist(输出文件)、node_modules(安装包)。
现在在src下添加一个print.js文件:
export default function(){
alert("I come from print.js");
}
修改index.js文件:
import fn from './print';
const btn = document.createElement("button");
btn.innerText = "Click me";
btn.onclick = fn;
document.body.appendChild(btn);
修改webpack.config.js文件的entry和output选项:
module.exports = {
entry:{
app:'./src/index.js',
print:'./src/print.js'
},
output:{
filename:"[name].bundle.js",
path:path.resolve(__dirname,'dist')
}
}
命令行运行npm run build,会发现在dist下生成2个文件:app.bundle.js、print.bundle.js。
app.bundle.js相当于之前的bundle.js文件,而print.bundle.js相当于单独对print.js文件的打包。
之前我们的index.html文件一直是手动修改的,打包了新的js文件,就要重新引入,很麻烦,所以我们来看看html-webpack-plugin能干什么。
设置htmlWebpackPlugin插件
先安装:
npm install --save-dev html-webpack-plugin
配置webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:{
app:'./src/index.js',
print:'./src/print.js'
},
plugins:[
new HtmlWebpackPlugin({
title:"输出管理"
})
],
output:{
filename:"[name].bundle.js",
path:path.resolve(__dirname,'dist')
}
}
命令行运行命令,你会发现除了生成之前的2个js文件,index.html文件也被更改了,title就是我们设置的title,2个脚本也被自动加载了。
默认该插件会自动在dist目录生成index.html文件,如果存在该文件,则覆盖替换。
更多参数配置及细节可以参考:https://github.com/jantimon/html-webpack-plugin
清空/dist目录
默认webpack每次编译后,都会保留之前编译好的文件,即使这些文件已经不再需要了。所以可以通过clean-webpack-plugin插件在编译完成之前 ,先清空dist目录。
npm install --save-dev clean-webpack-plugin
配置webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry:{
app:'./src/index.js',
print:'./src/print.js'
},
plugins:[
new HtmlWebpackPlugin({
title:"输出管理"
}),
new CleanWebpackPlugin(['dist'])
],
output:{
filename:"[name].bundle.js",
path:path.resolve(__dirname,'dist')
}
}
命令行运行命令。